package com.itheima.service.impl;

import com.itheima.controller.Code;
import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.domain.PageBean;
import com.itheima.exception.BussinessException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    public boolean save(Book book) {

        return bookDao.save(book)>0;
    }

    public boolean update(Book book) {

        return bookDao.update(book)>0;
    }

    public boolean delete(Integer id) {

        return bookDao.delete(id)>0;
    }

    public Book getById(Integer id) {
//
        if (id == 1) {
            throw new BussinessException(Code.BUSINESS_ERR, "请不要使用你的技术挑战我的耐性");
        }
//
//        try {
//            int i = 1 / 0;
//        } catch (Exception e) {
//            throw new BussinessException(Code.SYSTEM_TIMEOUT_ERR, "服务器访问超时,请检查你网络", e);
//
//        }
        return bookDao.getById(id);
    }

    public List<Book> getAll() {
        return bookDao.getAll();
    }

    @Override
    public PageBean<Book> getByPages(int currentPage, int pageSize) {
        //计算开始索引
        int begin=(currentPage-1)*pageSize;
        //计算查询条目数
        int size=pageSize;

        //查询当前页数据
        List<Book> rows = bookDao.getByPage(begin,size);
        int totalCount = bookDao.getTotalCount();
        PageBean<Book> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);
        return pageBean;
    }
}
